package com.mjlf.timer.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @ClassName Server
 * @auther mjlf
 * @Date 2019/9/23 9:36
 * @Description netty客户端
 */
public class Client {

    public static void main(String[] args) throws InterruptedException {
        //用于进行SocketChannel网络读写
        EventLoopGroup work = new NioEventLoopGroup();

        try {
            //netty用于启动NIO服务器的辅助启动类
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(work)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    //行解析器， 当遇到换行符的时候就认为是一个完成的报文，如果遇到长度超过1024还没有换行符，
                                    //那么将会抛出异常
                                    .addLast(new LineBasedFrameDecoder(1024))
                                    .addLast(new StringEncoder())
                                    .addLast(new StringDecoder())
                                    .addLast(new TimeClientHandler());
                        }
                    });
            //绑定端口返回ChannelFuture，用于异步处理
            ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 9090));
            //等待服务端链路关闭后main函数才退出
            future.channel().closeFuture().sync();
        }catch (Exception e){

        }finally {
            work.shutdownGracefully();
        }
    }

    static class TimeClientHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            for(int i = 0; i < 100; i++){
                ctx.channel().writeAndFlush("xx"+System.getProperty("line.separator"));
            }
        }
    }
}
